package com.ruoyi.website.gateway.config;

import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import com.ruoyi.common.core.utils.StringUtils;
import org.springdoc.core.AbstractSwaggerUiConfigProperties;
import org.springdoc.core.SwaggerUiConfigProperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.reactive.DefaultCorsProcessor;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * SpringDoc配置类
 *
 * @author houyong
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(value = "springdoc.api-docs.enabled", matchIfMissing = true)
public class SpringDocConfig implements InitializingBean {
    @Autowired
    private SwaggerUiConfigProperties swaggerUiConfigProperties;

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 在初始化后调用的方法
     */
    @Override
    public void afterPropertiesSet() {
        NotifyCenter.registerSubscriber(new SwaggerDocRegister(swaggerUiConfigProperties, discoveryClient));
    }
    
    /**
     * 配置跨域支持
     */
    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOriginPatterns(Arrays.asList("*"));
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setAllowCredentials(true);
        // 修复生产环境Swagger跨域问题
        config.setMaxAge(3600L);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        
        // 增强跨域处理器以更好地支持Swagger UI
        DefaultCorsProcessor corsProcessor = new DefaultCorsProcessor();
        
        return new CorsWebFilter(source, corsProcessor);
    }
}

/**
 * Swagger文档注册器
 */
class SwaggerDocRegister extends Subscriber<InstancesChangeEvent> {
    @Autowired
    private SwaggerUiConfigProperties swaggerUiConfigProperties;

    @Autowired
    private DiscoveryClient discoveryClient;

    private final static String[] EXCLUDE_ROUTES = new String[]{"ruoyi-website-gateway","ruoyi-gateway", "ruoyi-auth","ruoyi-system", "ruoyi-monitor"};

    public SwaggerDocRegister(SwaggerUiConfigProperties swaggerUiConfigProperties, DiscoveryClient discoveryClient) {
        this.swaggerUiConfigProperties = swaggerUiConfigProperties;
        this.discoveryClient = discoveryClient;
    }

    /**
     * 事件回调方法，处理InstancesChangeEvent事件
     *
     * @param event 事件对象
     */
    @Override
    public void onEvent(InstancesChangeEvent event) {
        Set<AbstractSwaggerUiConfigProperties.SwaggerUrl> swaggerUrlSet = discoveryClient.getServices()
                .stream()
                .flatMap(serviceId -> discoveryClient.getInstances(serviceId).stream())
                .filter(instance -> !StringUtils.equalsAnyIgnoreCase(instance.getServiceId(), EXCLUDE_ROUTES))
                .flatMap(instance -> {
                    // 为CMS服务创建分组
                    if ("ruoyi-cms".equals(instance.getServiceId())) {
                        Set<AbstractSwaggerUiConfigProperties.SwaggerUrl> cmsUrls = new HashSet<>();

                        // CMS网站端分组
                        AbstractSwaggerUiConfigProperties.SwaggerUrl websiteUrl = new AbstractSwaggerUiConfigProperties.SwaggerUrl();
                        websiteUrl.setName("cms-website");
                        // 修复生产环境Swagger跨域问题 - 使用兼容性更好的URL格式
                        websiteUrl.setUrl("/ruoyi-cms/v3/api-docs/cms-website");

                        cmsUrls.add(websiteUrl);
//
//                        // CMS管理端分组
//                        // AbstractSwaggerUiConfigProperties.SwaggerUrl managerUrl = new AbstractSwaggerUiConfigProperties.SwaggerUrl();
//                        // managerUrl.setName("cms-manager");
//                        // managerUrl.setUrl("/ruoyi-cms/v3/api-docs?group=cms-manager");
//                        // cmsUrls.add(managerUrl);
//
                        return cmsUrls.stream();
                    } else {
                        // 其他服务保持原有逻辑
                        AbstractSwaggerUiConfigProperties.SwaggerUrl swaggerUrl = new AbstractSwaggerUiConfigProperties.SwaggerUrl();
                        swaggerUrl.setName(instance.getServiceId());
                        swaggerUrl.setUrl(String.format("/%s/v3/api-docs", instance.getServiceId()));
                        return java.util.stream.Stream.of(swaggerUrl);
                    }
                })
                .collect(Collectors.toSet());

        swaggerUiConfigProperties.setUrls(swaggerUrlSet);
    }

    /**
     * 订阅类型方法，返回订阅的事件类型
     *
     * @return 订阅的事件类型
     */
    @Override
    public Class<? extends Event> subscribeType() {
        return InstancesChangeEvent.class;
    }
}